//
//  SPCLookSpaceViewController.swift
//  aj
//
//  Created by leeqb on 1/17/16.
//  Copyright © 2016 powerlee. All rights reserved.
//

import UIKit

class SPCLookSpaceViewController: AJBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, BottomButtonDelegate, UIAlertViewDelegate, SpaceEditPopupViewDelegate {
    var editFlag = false
    var userId: String!
    var familyId: String!
    var memberList = [NSDictionary]()
    var albumList = [[NSObject : AnyObject]]()
    var currentRowData: NSDictionary!
    var prevCell: UICollectionViewCell!
    var cellSize: CGSize!
    var editButtonsView: BottomButton!
    var popWin: SpaceEditPopupView!
    var albumListVC: AlbumListCollectionViewController!
    @IBOutlet weak var memberCollectionView: UICollectionView!
    @IBOutlet weak var albumListView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tabBarController!.tabBar.hidden = true
        memberCollectionView.delaysContentTouches = false
        
        albumListVC = LB("Common", vcName: "AlbumListVC") as! AlbumListCollectionViewController
        albumListVC.addFlag = true
        albumListVC.view.frame = CGRect(x: 0, y: 0, width: albumListView.frame.width, height: albumListView.frame.height)
        self.albumListView.addSubview(albumListVC.view)
        
        self.initData()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController!.tabBar.hidden = true
        self.requestData()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        if editButtonsView != nil {
            editFlag = false
            editButtonsView.hide()
            editButtonsView = nil
        }
    }
    
    //MARK: - Private Methods
    private func initData() {
        let addImage = UIImage(named: "album_add.png")
        let cellWidth = (SCREEN_WIDTH - 20) / 2
        let scale = cellWidth / (addImage?.size.width)!
        let cellHeight = (addImage?.size.height)! * scale + 26
        cellSize = CGSize(width: cellWidth, height: cellHeight)
    }
    
    private func requestData() {
        let params = ["userId": userId, "familyId": familyId]
        AJNetworkHelper.instance.post("aj_zone_by_family_list", parameters: params, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            let result = responseObject["result"] as! NSDictionary
            let albumList = result["AlbumList"] as? [[NSObject : AnyObject]]
            
            self.memberList.removeAll()
            let fatherInfo = result["userInfo"]!["left"] as? NSDictionary
            if fatherInfo != nil { // 爸爸
                self.memberList.append(["type": TITLE_FATHER, "data": fatherInfo!])
            }
            
            let childrenList = result["userInfo"]!["mid"] as? [NSDictionary]
            if childrenList?.count > 0 {
                var imagePaths = [String]()
                for ele in childrenList! {
                    imagePaths.append(ele["photo"] as? String ?? "")
                }
                self.memberList.append(["type": "子女", "data": imagePaths])
            }
            
            let motherInfo = result["userInfo"]!["right"] as? NSDictionary
            if motherInfo != nil { // 妈妈
                self.memberList.append(["type": TITLE_MOTHER, "data": motherInfo!])
            }
            
            self.albumList.removeAll()
            if albumList != nil && albumList?.count > 0 {
                for var ele in albumList! {
                    ele["checked"] = false
                    self.albumList.append(ele)
                }
            }
            
            self.memberCollectionView.reloadData()
            self.albumListVC.albumListData = result["AlbumList"] as? [NSDictionary]
            }, failed: { (operatin: AFHTTPRequestOperation!, error: NSError!) -> Void in
            }) { () -> Void in
                CBMessage.shareInstance().dismiss()
        }
    }
    
    private func deleteSpace(ids: String) {
        let params = ["oper": "3", "albumId": ids]
        CBMessage.shareInstance().showProcessing()
        AJNetworkHelper.instance.post("aj_album_mgr", parameters: params, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            if responseObject["returnCode"] as? String == RetCodeSuccess {
                self.editFlag = false
                self.editButtonsView.hide()
                self.editButtonsView = nil
                self.prevCell = nil
                //CBAlertView.shareInstance().showMsg("删除成功")
            } else {
                CBAlertView.shareInstance().showMsg(responseObject["errorMsg"] as? String)
            }
            self.requestData()
            }, failed: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                CBMessage.shareInstance().dismiss()
                CBAlertView.shareInstance().showMsg("删除失败")
            }) { () -> Void in
        }
    }

    //MARK: - Button Clicks
    @IBAction func editSpaceClick(sender: UIButton) {
        if editFlag {
            editFlag = false
            editButtonsView.hide()
            editButtonsView = nil
        } else {
            editFlag = true
            editButtonsView = BottomButton.getInstance()
            editButtonsView.delegate = self
            editButtonsView.buttons = [["title": "修改名称", "image": "spc_btn_name_edit_n"],
                ["title": "删除所选", "image": "spc_btn_del_sel_n"],
                ["title": "删除全部", "image": "spc_btn_del_all_n"]
            ]
            editButtonsView.show()
        }
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSize(width: 100, height: 140)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.memberList.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell: UICollectionViewCell!
        
        //if collectionView.tag == 1 {
        let rowData = self.memberList[indexPath.row]
        let type = rowData["type"] as! String
        if type == TITLE_MOTHER || type == TITLE_FATHER {
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemberCellParents", forIndexPath: indexPath)
            let imageView = cell.viewWithTag(1) as! UIImageView
            let nameLabel = cell.viewWithTag(2) as! UILabel
            let accountLabel = cell.viewWithTag(3) as! UILabel
            
            imageView.sd_setImageWithURL(NSURL(string: rowData["photo"] as? String ?? ""), placeholderImage: g_defaultImage)
            nameLabel.text = rowData["data"]!["nickName"] as? String ?? "无昵称"
            accountLabel.text = "(\((rowData["data"]!["ajNo"] as? String ?? "")!))"
        } else {
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemberCellChildren", forIndexPath: indexPath)
            let iconView = cell.viewWithTag(1) as! GroupedIconView
            let nameLabel = cell.viewWithTag(2) as! UILabel
            let accountLabel = cell.viewWithTag(3) as! UILabel
            
            iconView.imagePaths = rowData["data"] as! [String]
            nameLabel.text = "爱家宝宝"
            accountLabel.text = ""
        }
        /*} else {
            if indexPath.row == self.albumList.count {
                cell = collectionView.dequeueReusableCellWithReuseIdentifier("AddSpaceCell", forIndexPath: indexPath)
            } else {
                cell = collectionView.dequeueReusableCellWithReuseIdentifier("SpaceCell", forIndexPath: indexPath)
                
                let imageView = cell.viewWithTag(1) as! UIImageView
                let textLabel = cell.viewWithTag(2) as! UILabel
                let checkImageView = cell?.viewWithTag(4) as! UIImageView
                
                let data = self.albumList[indexPath.row]
                let defaultImage = UIImage(named: "album_no_photo.png")
                imageView.sd_setImageWithURL(NSURL(string: (data["zoneUrl"] as? String ?? "")), placeholderImage: defaultImage)
                textLabel.text = "\((data["zoneName"])!)(\((data["photoNumber"])!))张"
                
                if data["checked"] == nil || (data["checked"] as! Bool) == false {
                    checkImageView.image = UIImage(named: "spc_uncheck.png")
                } else {
                    checkImageView.image = UIImage(named: "spc_checked.png")
                }
                
                if editFlag {
                    checkImageView.hidden = false
                } else {
                    checkImageView.hidden = true
                }
            }
            
            if cell.selectedBackgroundView == nil {
                let backgroundView = UIView()
                backgroundView.backgroundColor = UIColor.orangeColor()
                cell.selectedBackgroundView = backgroundView
            }
            
            let borderView = cell.viewWithTag(3)!
            borderView.layer.borderWidth = 0.5
            borderView.layer.borderColor = RGB(185, g: 185, b: 185).CGColor
        }*/
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: false)
        
        if collectionView.tag == 1 {
            
        } else {
            if indexPath.row == self.albumList.count {
                let vc = LB("Space", vcName: "SpaceEditVC") as! UIViewController
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                if editFlag {
                    // 将上一个点击的Cell设置为非选中状态
                    if prevCell != nil {
                        let prevCheckImageView = prevCell.viewWithTag(4) as! UIImageView
                        let prevIndexPath = collectionView.indexPathForCell(prevCell)
                        var prevRowData = self.albumList[prevIndexPath!.row]
                        prevRowData["checked"] = false
                        self.albumList[prevIndexPath!.row] = prevRowData
                        prevCheckImageView.image = UIImage(named: "spc_uncheck.png")
                    }
                    
                    // 将当前点击的Cell设置为选中状态
                    let cell = collectionView.cellForItemAtIndexPath(indexPath)
                    let checkImageView = cell?.viewWithTag(4) as! UIImageView
                    var data = self.albumList[indexPath.row]
                    if data["checked"] == nil || (data["checked"] as! Bool) == false {
                        data["checked"] = true
                        checkImageView.image = UIImage(named: "spc_checked.png")
                    } else {
                        data["checked"] = false
                        checkImageView.image = UIImage(named: "spc_uncheck.png")
                    }
                    self.currentRowData = data
                    self.albumList[indexPath.row] = data
                    self.prevCell = cell
                } else {
                    let rowData = self.albumList[indexPath.row]
                    let vc = LB("Space", vcName: "AlbumPhotoListController") as! SPCAlbumPhotoListViewController
                    vc.zoneId = rowData["zoneId"] as! Int
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
    }
    
    @IBAction func addNewSpace(sender: UIButton) {
        let vc = LB("Space", vcName: "SpaceEditVC") as! UIViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: - BottomButtonDelegate
    func bottomButtonClick(index: Int) {
        switch index {
        case 0:
            // 弹出修改框
            //print(currentRowData)
            popWin = SpaceEditPopupView()
            popWin.delegate = self
            popWin.spaceInfo = currentRowData
            popWin.show()
        case 1:
            if self.currentRowData == nil {
                CBAlertView.shareInstance().showMsg("请选择一个空间")
                return
            }
            
            let alertView = UIAlertView(title: "温馨提示", message: "确定要删除当前空间吗？", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
            alertView.tag = 1
            alertView.show()
        case 2:
            let alertView = UIAlertView(title: "温馨提示", message: "确定要删除全部空间吗？", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
            alertView.tag = 2
            alertView.show()
        default:
            break
        }
    }
    
    //MARK: - UIAlertViewDelegate
    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            if alertView.tag == 1 {
                self.deleteSpace("\(currentRowData["zoneId"]!)")
            } else if alertView.tag == 2 {
                var ids = ""
                for ele in self.albumList {
                    ids += ele["zoneId"] as! String + ","
                }
                
                if !ids.isEmpty {
                    ids = ids.substringToIndex(ids.endIndex.advancedBy(-1))
                    self.deleteSpace(ids)
                }
            }
        }
    }
    
    // MARK: - BottomButtonDelegate
    func bottomButtonDidShow(buttonView: BottomButton) {
        /*var contentSize = self.albumCollectionView.contentSize
        contentSize.height += buttonView.view.frame.size.height
        self.albumCollectionView.contentSize = contentSize*/
    }
    
    func bottomButtonDidDismiss(buttonView: BottomButton) {
        /*var contentSize = self.albumCollectionView.contentSize
        contentSize.height -= buttonView.view.frame.size.height
        self.albumCollectionView.contentSize = contentSize
        
        editFlag = false
        self.albumCollectionView.reloadData()*/
    }
    
    // MARK: - SpaceEditPopupViewDelegate
    func spaceEditSuccess(responseObject: AnyObject) {
        self.editButtonsView.hide()
        self.requestData()
    }
    
}
